package java.com.clyz.material;

import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;

/**
 * 测试 需要 登录 得 Control
 *
 * @author Zemin.Yang
 * @date 2020/5/26 15:10
 */
@Slf4j
public abstract class AMockLoginTestControl {
    protected MockMvc mockMvc;

    protected void runJson(String request, String url) throws Exception {
        MockHttpServletRequestBuilder requestBuilder;
        if(StringUtils.isNotBlank(request)){
            requestBuilder = MockMvcRequestBuilders
                    .post(url)
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(request);
        }else {
            requestBuilder = MockMvcRequestBuilders
                    .post(url)
                    .contentType(MediaType.APPLICATION_JSON);
        }


        final ResultActions perform = getMockMvc().perform(requestBuilder);
        perform.andExpect(MockMvcResultMatchers.status().isOk());

        final MockHttpServletResponse response = perform.andReturn().getResponse();
        log(response);
    }

    /**
     * HttpHeaders headers = new HttpHeaders();
     */
    protected void runFrom(MultiValueMap<String, String> params, String url) throws Exception {

        final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders
                .post(url);
        if (!ObjectUtils.isEmpty(params)) {
            requestBuilder.params(params);
        }

        final ResultActions perform = getMockMvc().perform(requestBuilder);
        perform.andExpect(MockMvcResultMatchers.status().isOk());

        final MockHttpServletResponse response = perform.andReturn().getResponse();
        log(response);
    }

    protected MockMvc getMockMvc() {
        return mockMvc;
    }

    protected void log(MockHttpServletResponse response) throws UnsupportedEncodingException {
        log.info(response.getContentAsString());
    }

}
